package com.xdl.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beluga.core.util.Func;
import com.xdl.configuration.BaseContextHandler;
import com.xdl.modules.dto.WxOwnerCouponDto;
import com.xdl.modules.entity.WxCoupon;
import com.xdl.modules.entity.WxOwnerCoupon;
import com.xdl.modules.mapper.WxOwnerCouponMapper;
import com.xdl.modules.model.WxOwnerCouponModel;
import com.xdl.modules.service.WxCouponService;
import com.xdl.modules.service.WxOwnerCouponService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author iron guo
 * @since 2022-04-27
 */
@Service
@AllArgsConstructor
public class WxOwnerCouponServiceImpl extends ServiceImpl<WxOwnerCouponMapper, WxOwnerCoupon> implements WxOwnerCouponService {

    private WxCouponService couponService;


    /**
     * 领取优惠券
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Boolean putCoupon(Long id) {
        QueryWrapper<WxOwnerCoupon> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(WxOwnerCoupon::getUserId,BaseContextHandler.getUserID())
                .eq(WxOwnerCoupon::getCouponId,id);
        Integer count = this.baseMapper.selectCount(wrapper);
        if(count>0){
            return false;
        }
        WxCoupon wxCoupon = couponService.getById(id);
        WxOwnerCoupon owner = new WxOwnerCoupon();
        if (Func.isEmpty(wxCoupon.getValidity())) {
            owner.setStartDay(wxCoupon.getStartDay());
            owner.setEndDay(wxCoupon.getEndDay());
        } else {
            LocalDate localDate = LocalDate.now();
            owner.setStartDay(localDate.atStartOfDay());
            owner.setEndDay(localDate.plus(wxCoupon.getValidity(), ChronoUnit.DAYS).atStartOfDay());
        }
        owner.setCouponId(wxCoupon.getId());
        owner.setStatus(1);
        owner.setUserId(Long.valueOf(BaseContextHandler.getUserID()));
        int insert = this.baseMapper.insert(owner);
        return insert > 0;
    }

    /**
     * 获取我的优惠券列表
     * @param model
     * @return
     */
    @Override
    public List<WxOwnerCouponDto> getCouponList(WxOwnerCouponModel model) {
        return this.baseMapper.getCouponList(new Page<>(model.getPageNo(), model.getPageSize()),model.getStatus(),model.getRule(),BaseContextHandler.getUserID());
    }
}
